<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="电子书名称" v-model="keyword">
      </el-input>

      <!-- <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.type" placeholder="类型">
        <el-option v-for="item in  typeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key">
        </el-option>
      </el-select> -->

      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="primary" @click="handleCreate"  icon="edit">添加</el-button>

      <el-button class="filter-item" type="primary" @click="handleDelAll"  icon="edit">批量删除</el-button>

    </div>

    
   
    <!-- 表格 -->
    <el-table style="font-size:13px;width: 100%" ref="multipleTable" 
    @selection-change="handleSelectionChange" 
    :data="ebooks" border fit highlight-current-row  >
         <el-table-column type="selection" width="40">
         </el-table-column>

          <el-table-column align="center" label='序号' width="65">
            <template slot-scope="scope">
              {{scope.row.ebook_id}}
            </template>
          </el-table-column>

          <el-table-column align="center"  label="封面"  width="100" >
                <template slot-scope="scope">
                  <el-image :src="scope.row.ebook_cover" :lazy="true" fit="cover"></el-image>
                </template>
            </el-table-column>

          <el-table-column label="电子书名称" align="center" width="180">
            <template slot-scope="scope">
              {{scope.row.ebook_title}}
            </template>
          </el-table-column>

          <el-table-column label="类别" align="center" width="90">
            <template slot-scope="scope">
               {{scope.row.type_title}}
            </template>
          </el-table-column>

          <el-table-column label="作者"  align="center" width="100">
            <template slot-scope="scope">
              {{scope.row.ebook_author}}  
            </template>
          </el-table-column>

          <el-table-column align="center"  label="简介" width="200">
            <template slot-scope="scope">
              {{scope.row.ebook_eintro |simpleIntro}}  
            </template>
          </el-table-column>

          <el-table-column label="标签" align="center" width="70">
            <template slot-scope="scope">
              {{scope.row.ebook_tag}}
            </template>
          </el-table-column>

          <!-- <el-table-column label="评分" align="center" width="70">
            <template slot-scope="scope">
              {{scope.row.ebook_grade}}
            </template>
          </el-table-column> -->

        <el-table-column label="ISBN" align="center" width="70">
            <template slot-scope="scope">
              {{scope.row.ebook_ISBN }}
            </template>
          </el-table-column>
          <el-table-column label="发布时间" align="center" width="100">
            <template slot-scope="scope">
              {{scope.row.ebook_ctime |simpleTime}}
            </template>
          </el-table-column>

            <el-table-column label="书籍url" align="center" width="200">
            <template slot-scope="scope">
              {{scope.row.ebook_url}}
            </template>
          </el-table-column>

            <el-table-column align="center"  label="操作" fixed="right" width="150">
                <template slot-scope="scope">
                    
                   <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                   <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                         
                </template>
            </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.currPage"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  computed:{
    ...mapGetters(
      ['userInfo']
    )
  },
  filters:{
    simpleIntro(intros){
      return intros.length>50?intros.substring(0,51)+'...':intros
    },
    simpleTime(times){
      let date = new Date(times),
        year = date.getFullYear(),
        month = date.getMonth() +1,
        day = date.getDate();
      return `${year}-${month}-${day}`
    }
  },
  data() {
    return {
        list: null,//表格list [].push({})
        // 页面总数
        total: null,
        // 请求数据数量和当前页面
        listQuery: {
            currPage: 1,
            pageSize: 10
        },
        ebooks:[] ,//展示的ebooks
        keyword:'', //搜索的关键词

        typeOptions:[
          { key: '001', display_name: '类型1' },
          { key: '002', display_name: '类型2' },
          { key: '003', display_name: '类型3' }
         
        ],
        dialogFormVisible: false,
        multipleSelection: []

    }
  },
  async created() {
    this.getList();
  },
  methods: {
    
    //获取列表数据
   async  getList() {
        let user_id = this.userInfo.user_id
        let res = await this.$http.get('/get_ebooks',{params:{user_id, currPage:this.listQuery.currPage , pageSize: this.listQuery.pageSize}})
        this.listQuery.currPage = parseInt(res.data.currPage)
        this.listQuery.pageSize = parseInt(res.data.pageSize)
        this.total = parseInt(res.data.total)
        this.ebooks = res.data.ebooks
        console.log(res.data);
    },
    //编辑
   async handleEdit(row){
       // 获得电子书的类别
        let res = await this.$http.get('/get_ebook_types')
        row.types = res.data
        this.$store.commit('SET_EBOOK', row);
        console.log('编辑的row-----',row);
        //跳页面进行修改
       this.$router.push( { path: '/ebooksManage/ebookUpdate'}); //带参跳转
    },

    //单个删除
    handleDelete(index,row){
        let vm = this;
        console.log('单个删除选择的row：',index,'-----',row);
        
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
          vm.delFun(row);
          //前端删除。
            vm.ebooks.splice(index,1)
            this.$message({
              type: 'success',
              message: '删除成功!'
            });

        }).catch(() => {
          
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
        });

    },
    //调取删除接口的删除方法
    async delFun(row){
      await  this.$http.delete('/delete_ebook',{params:{ebook_id: row.ebook_id}})
    },
    //批量删除
    handleDelAll(){
        let vm = this;
        console.log('批量删除选择的row：',vm.multipleSelection)
        
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定批量删除',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            //前端依次执行单个删除操作
             vm.ebooks = vm.ebooks.filter((item)=>{
                for(let selection of vm.multipleSelection){
                  if(item.ebook_id === selection.ebook_id){
                    return false
                  }
                }
                return true;
              })
            for (var index in vm.multipleSelection) {
                console.log('======',vm.multipleSelection[index])
                vm.delFun(vm.multipleSelection[index]);    
            };
            
            this.$message({
              type: 'success',
              message: '删除成功!'
            });

        }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
        });
    },
    //搜索
   async  handleFilter() {
        let user_id = this.userInfo.user_id
        let res = await this.$http.get('/search_ebooks',{params:{user_id,keyword:this.keyword ,currPage:this.listQuery.currPage , pageSize: this.listQuery.pageSize}})
        this.listQuery.currPage = parseInt(res.data.currPage)
        this.listQuery.pageSize = parseInt(res.data.pageSize)
        this.total = parseInt(res.data.total)
        this.ebooks = res.data.ebooks
        console.log(res.data);
    },
    //操作分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.getList();
    },
    //操作分页
    handleCurrentChange(val) {
        console.log('--------',val)
      this.listQuery.currPage = val;
      this.getList();
    },
     //跳到新增页面
    handleCreate() {
        this.$router.push('/ebooksManage/ebookAdd')
    },
  
    handleSelectionChange(val) {
        this.multipleSelection = val;
    },

    handleDownload() {
      let vm = this;

      require.ensure([], () => {
        const { export_json_to_excel } = require('vendor/Export2Excel');
        const tHeader = ['字段1', '字段2', '字段3', '字段4', '字段5'];
        const filterVal = ['chnlId', 'hisChnlId', 'chnlName', 'state', 'isavailable'];
        const list = vm.list;
        const data = vm.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '导出的列表excel');
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
};
</script>
